<template>
    <div>
        <div class="page-header">
            <CustomTitle :title="route.meta.title" />
            <el-space>
                <el-button type="primary" @click="save">保存</el-button>
                <el-button type="primary" plain @click="colseVisible = true">取消</el-button>
            </el-space>
        </div>
        <el-scrollbar max-height="calc(100vh - 200px)">
            <div class="fittings-params-form">
                <el-form :model="params" label-width="auto" ref="formRef" :rules="rules">
                    <el-form-item label="商品附加信息模板名称" prop="name">
                        <el-input placeholder="请输入模板名称" v-model="params.name" />
                    </el-form-item>
                    <el-form-item label="商品附加信息备注方式">
                        <el-radio-group v-model="type">
                            <el-radio :value="1">文本备注（被关联的商品，在商城前台会在覆盖在商品的所有SKU上）</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="商品附加信息" prop="content">
                        <el-input type="textarea" v-model="params.content"
                            placeholder="被关联的商品在设计师商城前端会出现此项备注内容，“如，送杯子”" />
                    </el-form-item>
                    <el-form-item label="备注" prop="remark">
                        <el-input type="textarea" v-model="params.remark" placeholder="请输入备注信息" />
                    </el-form-item>
                </el-form>
            </div>
            <div class="dividing"></div>
            <div class="app-container">
                <div class="table-head-btn">
                    <el-input placeholder="搜索商品名称或商品ID" v-model="keyword" :suffix-icon="Search" />
                    <el-space>
                        <el-button type="primary" plain @click="cancelRelated(null)">批量取消关联</el-button>
                        <el-button type="primary" @click="addRelated">
                            添加关联商品
                        </el-button>
                    </el-space>
                </div>
                <el-row class="table-head">
                    <el-col :span="1">
                        <el-checkbox @change="setCheckAll" v-model="checkAll"
                            :indeterminate="isIndeterminate"></el-checkbox>
                    </el-col>
                    <el-col :span="2">
                        商品图
                    </el-col>
                    <el-col :span="5">
                        商品信息
                    </el-col>
                    <el-col :span="5">
                        更新时间
                    </el-col>
                    <el-col :span="6">
                        展示状态
                    </el-col>
                    <el-col :span="5">
                        操作
                    </el-col>
                </el-row>
                <el-empty v-if="!list.length && !loading" />
                <div class="loading" v-if="loading && !list.length" v-loading="loading"></div>
                <el-checkbox-group v-model="checkedList">
                    <el-row class="table-item" v-for="item in list" :key="item.id">
                        <el-col :span="1">
                            <el-checkbox :value="item.collectId" @change="checked"></el-checkbox>
                        </el-col>
                        <el-col :span="2">
                            <img :src="item.mainPicUrl" alt="">
                        </el-col>
                        <el-col :span="5">
                            <div class="info">
                                <div class="name">{{ item.productName }}</div>
                                <div>上架类目：{{ item.preview }}</div>
                                <div>型号：{{ item.businessModelCode }}</div>
                                <div>分类：{{ item.categoryName }}</div>
                                <div>ID：{{ item.collectId }}</div>
                            </div>
                        </el-col>
                        <el-col :span="5">
                            {{ item.updateTime }}
                        </el-col>
                        <el-col :span="6">
                            当前商品附加信息模板与此商品关联中
                        </el-col>
                        <el-col :span="5">
                            <el-button link type="primary" @click="cancelRelated(item)">取消关联</el-button>
                        </el-col>
                    </el-row>
                </el-checkbox-group>
                <div class="pagination">
                    <el-pagination v-model:current-page="goodsParams.current" v-model:page-size="goodsParams.size"
                        :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                        :total="total" />
                </div>
            </div>
        </el-scrollbar>
        <el-dialog v-model="sureVisibel" width="400" center align-center :show-close="false">
            <div class="sure">
                <div>
                    <el-icon>
                        <Warning />
                    </el-icon>
                </div>
                <span>是否确认移除此商品？</span>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="sureVisibel = false">取消</el-button>
                    <el-button type="primary" @click="confirm">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="colseVisible" width="400" center align-center :show-close="false">
            <div class="sure">
                <div>
                    <el-icon>
                        <Warning />
                    </el-icon>
                </div>
                <span>取消后，您设置的配件备注模板信息将被清除，请保存后在离开，确认要继续离开吗？</span>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="colseVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmColse">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import CustomTitle from "@/components/CustomTitle/index.vue";
import { Search } from '@element-plus/icons-vue';
import { getRelatedListById, addTemplate, editTemplate } from "@/apis/stencil/fittings";
import { useStencilStore } from "@/store";
import { ElMessage } from "element-plus";

const stencilStore = useStencilStore();
const keyword = ref('');
const form = ref({});
const route = useRoute();
const router = useRouter();
const goodsParams = ref({
    current: 1,
    size: 10
});
const formRef = ref(null)
const colseVisible = ref(false);
const batchList = ref([]);
const sureVisibel = ref(false);
const data = ref([]);
const params = ref({
    collectIds: [],
    remark: route.query.remark,
    content: route.query.content,
    name: route.query.name,
})
const total = ref(0)
const checkedList = ref([])
const type = ref(1);
const checkAll = ref(false);
const isIndeterminate = ref(false);
const loading = ref(false)
const init = async () => {
    const res = await getRelatedListById(route.query.id);
    data.value = res.data;
    loading.value = false;
}
const confirmColse = () => {
    router.push('/stencil/fittings');
    stencilStore.relatedList = []
}
/**
 * 选择
 */
const checked = () => {
    checkAll.value = checkedList.value.length == [...data.value, ...stencilStore.relatedList].length;
    isIndeterminate.value = checkedList.value.length != [...data.value, ...stencilStore.relatedList].length && checkedList.value.length != 0;
}
const list = computed(() => {
    if (keyword.value) {
        const tempList = [...data.value, ...stencilStore.relatedList].filter(v => v.productName.indexOf(keyword.value) != -1 || v.collectId.indexOf(keyword.value) != -1);
        total.value = tempList.length;
        return tempList;
    } else {
        total.value = [...data.value, ...stencilStore.relatedList].length;
        const start = goodsParams.value.current * goodsParams.value.size - goodsParams.value.size;
        const end = goodsParams.value.current * goodsParams.value.size;
        return [...data.value, ...stencilStore.relatedList].slice(start, end)
    }
})
const addRelated = () => {
    const query = {
        ...params.value,
        id: route.query.id
    }
    delete query.collectIds;
    router.push({
        path: '/stencil/fittings/related',
        query
    })
}
const rules = {
    name: [
        { required: true, message: '请输入关联名称', trigger: 'blur' },
        { max: 20, message: "请输入20位以内的字符", trigger: 'blur' }
    ],
    content: [
        { required: true, message: '请输入关联内容', trigger: 'blur' },
        { max: 40, message: "请输入40位以内的字符", trigger: 'blur' }
    ],
    remark: [
        { max: 40, message: "请输入40位以内的字符", trigger: 'blur' }
    ]
}
/**
 * 取消关联
 */
const cancelRelated = (item) => {
    if (item || checkedList.value.length) {
        if (item) {
            batchList.value = [item].map(v => v.collectId);
        } else {
            batchList.value = [...data.value, ...stencilStore.relatedList].filter(v => checkedList.value.includes(v.collectId)).map(v => v.collectId);
        }
        sureVisibel.value = true;
    } else {
        ElMessage.error('请选择要取消关联的商品');
    }
}
/**
 * 确认取消
 */
const confirm = () => {
    batchList.value.forEach((item) => {
        const isData = data.value.some(v => v.collectId == item);
        const isStore = stencilStore.relatedList.some(v => v.collectId == item);
        if (isData) {
            data.value.splice(data.value.findIndex(v => v.collectId == item), 1);
        }
        if (isStore) {
            stencilStore.relatedList.splice(stencilStore.relatedList.findIndex(v => v.collectId == item), 1);
        }
    });
    checkedList.value = [];
    checked();
    ElMessage.success('取消关联成功,保存生效！');
    sureVisibel.value = false;
}
/**
 * 设置全选
 */
const setCheckAll = () => {
    checkedList.value = checkAll.value ? [...data.value, ...stencilStore.relatedList].map(item => item.collectId) : [];
    isIndeterminate.value = false;
};
/**
 * 保存
 */
const save = async () => {
    const callback = () => {
        ElMessage.success('保存成功');
        router.push('/stencil/fittings');
        stencilStore.relatedList = []
    }
    formRef.value.validate(async (valid) => {
        if (valid) {
            if (route.query.id) {
                const collectIds = [...data.value, ...stencilStore.relatedList].map(v => v.collectId);
                const paramsData = { ...params.value, id: route.query.id, collectIds };
                delete paramsData.type;
                const res = await editTemplate(paramsData);
                if (res.code == 200) {
                    callback()
                }
            } else {
                const res = await addTemplate(params.value);
                if (res.code == 200) {
                    callback()
                }
            }
        }
    })
}
onMounted(() => {
    if (route.query.id) {
        loading.value = true;
        init();
    }
    if (stencilStore.relatedList.length) {
        params.value.collectIds = stencilStore.relatedList.map(item => item.collectId);
    }
})
</script>

<style lang="scss" scoped>
@import 'index'
</style>